package com.jinyi.wwdeng.autodialer.utils

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.jinyi.wwdeng.autodialer.service.AutoCallService

/**
 * Service状态检查工具类
 */
object ServiceUtil {

    /**
     * 检查服务是否正在运行
     */
    fun isServiceRunning(context: Context, serviceClass: Class<*>): Boolean {
        // 首先检查单例实例
        if (serviceClass == AutoCallService::class.java) {
            AutoCallService.isServiceRunning().let { return it }
        }

        // 通过ActivityManager检查
        val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningServices = manager.getRunningServices(Integer.MAX_VALUE)

        return runningServices.any { it.service.className == serviceClass.name }
    }

    /**
     * 安全启动服务（避免重复启动）
     */
    fun startAutoCallService(context: Context): Boolean {
        return if (isServiceRunning(context, AutoCallService::class.java)) {
            Log.w("ServiceUtils", "自动呼叫服务已在运行中，跳过启动")
            false
        } else {
            try {
                val intent = Intent(context, AutoCallService::class.java).apply {
                    action = AutoCallService.ACTION_START
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(intent)
                } else {
                    context.startService(intent)
                }
                Log.d("ServiceUtils", "自动呼叫服务启动请求已发送")
                true
            } catch (e: Exception) {
                Log.e("ServiceUtils", "启动自动呼叫服务失败", e)
                false
            }
        }
    }

    /**
     * 停止服务
     */
    fun stopAutoCallService(context: Context): Boolean {
        return try {
            val intent = Intent(context, AutoCallService::class.java).apply {
                action = AutoCallService.ACTION_STOP
            }
            context.startService(intent)
            Log.d("ServiceUtils", "自动呼叫服务停止请求已发送")
            true
        } catch (e: Exception) {
            Log.e("ServiceUtils", "停止自动呼叫服务失败", e)
            false
        }
    }

    /**
     * 获取服务状态信息
     */
    fun getServiceStatus(context: Context): String {
        val isRunning = isServiceRunning(context, AutoCallService::class.java)
        return if (isRunning) "服务运行中" else "服务已停止"
    }
}